package com.tencent.hummingbird.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tencent.hummingbird.portal.exception.ServiceException;
import com.tencent.hummingbird.portal.mapper.UserMapper;
import com.tencent.hummingbird.portal.pojo.User;
import com.tencent.hummingbird.portal.pojo.UserCollect;
import com.tencent.hummingbird.portal.mapper.UserCollectMapper;
import com.tencent.hummingbird.portal.service.IUserCollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yxb
 * @since 2024-01-10
 */
@Service
public class UserCollectServiceImpl extends ServiceImpl<UserCollectMapper, UserCollect> implements IUserCollectService {
    @Autowired
    private UserCollectMapper userCollectMapper;
    @Override
    public Integer countCollectsByUserId(Integer userId) {
        QueryWrapper<UserCollect> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        int count = userCollectMapper.selectCount(query);
        return count;
    }
    @Autowired
    private UserMapper userMapper;
    @Override
    public Integer cancelCollect(String username, Integer questionId) {
        User user = userMapper.findUserByUsername(username);
        Integer num = userCollectMapper.deleteCollect(user.getId(),questionId);
        return num;
    }

    @Override
    public void addCollect(String username, Integer questionId) {
        User user = userMapper.findUserByUsername(username);
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(user.getId())
                    .setQuestionId(questionId)
                    .setCreatetime(LocalDateTime.now());
        int num = userCollectMapper.insert(userCollect);
        if(num!=1){
            throw ServiceException.busy();
        }
    }

    @Override
    public Integer selectCollectStatus(String username, Integer questionId) {
        User user = userMapper.findUserByUsername(username);
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(user.getId())
                    .setQuestionId(questionId);
        int status = userCollectMapper.selectCollectStatus(userCollect);
        return status;
    }
}
